<template>
  <div class="ml-2 flex-1">
    <div>
      <a-card :bordered="false" style="height: 830px; width: 1380px">
        <a-form
          :model="searchForm"
          layout="inline"
          :label-col="labelCol"
          ref="searchFormRef"
        >
          <a-form-item label="收费操作人" name="receiver">
            <a-tree-select
              v-model:value="searchForm.receiver"
              tree-data-simple-mode
              allow-clear
              style="width: 260px"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="selectList"
              placeholder="请选择操作人"
              :load-data="onLoadData"
            />
          </a-form-item>
          <a-form-item label="收费时间" name="tradeDateRange">
            <a-range-picker
              v-model:value="searchForm.tradeDateRange"
              format="YYYY-MM-DD"
            />
          </a-form-item>
          <a-form-item label="费用类型" name="feeCategory">
            <a-select
              v-model:value="searchForm.feeCategory"
              placeholder="请选择"
              style="width: 200px"
            >
              <a-select-option value="交费">交费</a-select-option>
              <a-select-option value="退费">退费</a-select-option>
              <a-select-option value="交费-红冲">交费-红冲</a-select-option>
              <a-select-option value="退费-红冲">退费-红冲</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="热力卡号" name="alipayConsNo">
            <a-input
              v-model:value="searchForm.alipayConsNo"
              placeholder="请输入"
              style="width: 200px"
            />
          </a-form-item>
          <a-form-item label="收费期" name="yearRange">
            <a-range-picker
              v-model:value="searchForm.yearRange"
              format="YYYY"
              picker="year"
            />
          </a-form-item>
          <a-form-item label="冲账时间" name="redAccountDateRange">
            <a-range-picker
              v-model:value="searchForm.redAccountDateRange"
              format="YYYY-MM-DD"
            />
          </a-form-item>
          <a-form-item>
            <a-button
              type="primary"
              class="mr-3"
              :icon="h(SearchOutlined)"
              @click="onSearch"
              >查询</a-button
            >
            <a-button type="primary" :icon="h(RedoOutlined)" @click="onReset"
              >重置</a-button
            >
          </a-form-item>
        </a-form>
        <a-table
          :columns="columns"
          :data-source="dataSource"
          bordered
          :pagination="pagination"
          class="mt-5"
          :scroll="{ x: 3300, y: 500 }"
          :row-class-name="
            (_record: any, index: number) =>
              index % 2 === 1 ? 'table-striped' : null
          "
        >
          <template #bodyCell="{ column, record, text }">
            <template v-if="column.dataIndex === 'active'">
              <a-button type="link" @click="onOpen(record)">冲账</a-button>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>
    <a-modal v-model:open="open" title="新增红冲" @ok="handleOk" width="700px">
      <a-form :model="submitForm" :label-col="labelCol">
        <a-form-item label="交易流水ID">
          <a-input
            placeholder="交易流水ID"
            disabled
            style="width: 200px"
            v-model:value="receiptNo"
          />
        </a-form-item>
        <a-form-item label="冲账类型">
          <a-select
            v-model:value="submitForm.redAccountType"
            placeholder="请选择"
            style="width: 200px"
          >
            <a-select-option value="面积错误">面积错误</a-select-option>
            <a-select-option value="金额错误">金额错误</a-select-option>
            <a-select-option value="机构错误">机构错误</a-select-option>
            <a-select-option value="其他">其他</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="冲账原因">
          <a-textarea
            v-model:value="submitForm.redAccountReason"
            placeholder="请输入冲账原因"
            :rows="4"
            style="width: 200px"
          />
        </a-form-item>
        <div class="ml-7">
          <a-form-item label="附件">
            <a-upload
              v-model:file-list="fileList"
              action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              list-type="picture"
            >
              <a-button>
                <FolderAddOutlined />
                上传
              </a-button>
            </a-upload>
          </a-form-item>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, h } from 'vue';
import {
  SearchOutlined,
  RedoOutlined,
  FolderAddOutlined,
} from '@ant-design/icons-vue';
import { getRedChargeApi, getChargeApi } from '#/api/core/charge';
import dayjs from 'dayjs';
import { message } from 'ant-design-vue';
import { getOperatorApi } from '#/api/core/statistical';


const props = defineProps({
  selectedNodeId: {
    type: Array,
    default: [],
  },
});
const selectList = ref([]);
const getList = () => {
  getOperatorApi(null)
    .then((res: any) => {
      // console.log(res);
      selectList.value = res.map((item: any) => {
        return {
          id: item.id,
          value: item.id,
          title: item.name,
          key: item.id,
          isLeaf: !!item.userId, // 如果有userId说明是叶子节点
        };
      });
    })
    .catch((error) => {
      console.error('获取操作人员列表失败:', error);
      message.error('获取操作人员列表失败');
    });
};
getList();
const onLoadData = (treeNode: any) => {
  return new Promise((resolve) => {
    // console.log(treeNode);
    // 如果是叶子节点，直接返回
    if (treeNode.isLeaf) {
      resolve(undefined);
      return;
    }

    // 加载子节点数据
    getOperatorApi(treeNode.id)
      .then((res: any) => {
        const children = res.map((item: any) => {
          // console.log(item);
          return {
            id: item.userId ? item.userId : item.id,
            value: item.name ? item.name : item.name,
            title: item.name,
            key: item.userId ? item.userId : item.id,
            isLeaf: !!item.userId, // 如果有userId说明是叶子节点
          };
        });

        // 找到对应的节点并更新其children
        const updateNode = (nodes: any[]) => {
          for (let node of nodes) {
            if (node.key === treeNode.id) {
              node.children = children;
              return true;
            }
            if (node.children && updateNode(node.children)) {
              return true;
            }
          }
          return false;
        };

        updateNode(selectList.value);
        selectList.value = [...selectList.value];
        // console.log(selectList.value);
        resolve(undefined);
      })
      .catch((error) => {
        console.error('加载子节点失败:', error);
        message.error('加载子节点失败');
        resolve(undefined);
      });
  });
};
const searchFormRef = ref(null);
const open = ref(false);
const receiptNo = ref('');
const payfeeID = ref('');
const fileList = ref([]);
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const dataSource = ref([]);
const columns = [
  {
    title: '小区名称',
    dataIndex: 'village',
    key: 'village',
    align: 'center',
  },
  {
    title: '热力卡号',
    dataIndex: 'alipayConsNo',
    key: 'alipayConsNo',
    align: 'center',
  },
  {
    title: '住户名称',
    dataIndex: 'holder',
    key: 'holder',
    align: 'center',
  },
  {
    title: '用户地址',
    dataIndex: 'houseAddress',
    key: 'houseAddress',
    align: 'center',
  },
  {
    title: '收费期',
    dataIndex: 'year',
    key: 'year',
    align: 'center',
  },
  {
    title: '面积名称',
    dataIndex: 'areaName',
    key: 'areaName',
    align: 'center',
  },
  {
    title: '交易流水',
    dataIndex: 'journalNumber',
    key: 'journalNumber',
    align: 'center',
  },
  {
    title: '费用类型',
    dataIndex: 'feeCategory',
    key: 'feeCategory',
    align: 'center',
  },
  {
    title: '业务类型',
    dataIndex: 'businessType',
    key: 'businessType',
    align: 'center',
  },
  {
    title: '应收全费金额',
    dataIndex: 'normalReceivable',
    key: 'normalReceivable',
    align: 'center',
  },
  {
    title: '应收基本费金额',
    dataIndex: 'heatWasteReceivable',
    key: 'heatWasteReceivable',
    align: 'center',
  },
  {
    title: '缴款方式',
    dataIndex: 'tradeWay',
    key: 'tradeWay',
    align: 'center',
  },
  {
    title: '收费人',
    dataIndex: 'receiver',
    key: 'receiver',
    align: 'center',
  },
  {
    title: '收费时间',
    dataIndex: 'tradeDate',
    key: 'tradeDate',
    align: 'center',
  },
  {
    title: '冲账人',
    dataIndex: 'redAccountPerson',
    key: 'redAccountPerson',
    align: 'center',
  },
  {
    title: '冲账时间',
    dataIndex: 'redAccountDate',
    key: 'redAccountDate',
    align: 'center',
  },
  {
    title: '冲账原因',
    dataIndex: 'redAccountReason',
    key: 'redAccountReason',
    align: 'center',
  },
  {
    title: '违约金实收',
    dataIndex: 'lateFeeRealReceive',
    key: 'lateFeeRealReceive',
    align: 'center',
  },
  {
    title: '实付金额',
    dataIndex: 'tradeAmount',
    key: 'tradeAmount',
    align: 'center',
  },
  {
    title: '含预收账户金额',
    dataIndex: 'prepayAmount',
    key: 'prepayAmount',
    align: 'center',
  },
  // {
  //   title: "实收金额",
  //   dataIndex: "name",
  //   key: "name",
  //   align: "center",
  // },

  // {
  //   title: "操作人",
  //   dataIndex: "receiver",
  //   key: "receiver",
  //   align: "center",
  // },
  // {
  //   title: "审核状态",
  //   dataIndex: "name",
  //   key: "name",
  //   align: "center",
  // },
  {
    title: '是否冲账',
    dataIndex: 'isRedAccount',
    key: 'isRedAccount',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'active',
    key: 'active',
    align: 'center',
    fixed: 'right',
  },
];
const labelCol = { style: { width: '80px' } };
const searchForm = reactive({
  receiver: '',
  alipayConsNo: '',
  feeCategory: '',
  tradeDateRange: [],
  redAccountDateRange: [],
  yearRange: [],
});
const submitForm = reactive({
  redAccountType: '',
  redAccountReason: '',
  payUrl: 'http://testURL_ADDRESS',
});
const onSearch = () => {
  if (!props.selectedNodeId||props.selectedNodeId.length === 0) {
    message.error('请选择左侧树结构！');
    return;
  } else {
    console.log(searchForm);
    const data = {
      headerMessage: {
        receiver: searchForm.receiver,
        alipayConsNo: searchForm.alipayConsNo,
        feeCategory: searchForm.feeCategory,
        tradeDateBegin:
          searchForm.tradeDateRange.length != 0
            ? dayjs(searchForm.tradeDateRange[0]).format('YYYY-MM-DD HH:mm:ss')
            : '',
        tradeDateEnd:
          searchForm.tradeDateRange.length != 0
            ? dayjs(searchForm.tradeDateRange[1]).format('YYYY-MM-DD HH:mm:ss')
            : '',
        redAccountDateBegin:
          searchForm.redAccountDateRange.length != 0
            ? dayjs(searchForm.redAccountDateRange[0]).format(
                'YYYY-MM-DD HH:mm:ss',
              )
            : '',
        redAccountDateEnd:
          searchForm.redAccountDateRange.length != 0
            ? dayjs(searchForm.redAccountDateRange[1]).format(
                'YYYY-MM-DD HH:mm:ss',
              )
            : '',
        yearBegin:
          searchForm.yearRange.length != 0
            ? dayjs(searchForm.yearRange[0]).format('YYYY')
            : '',
        yearEnd:
          searchForm.yearRange.length != 0
            ? dayjs(searchForm.yearRange[1]).format('YYYY')
            : '',
      },
      treeData: props.selectedNodeId,
      page: pagination.current,
      limit: pagination.pageSize,
    };
    // console.log(data);
    getRedChargeApi(data).then((res) => {
      console.log(res);
      pagination.total = res.total;
      dataSource.value = res.data;
    });
  }
};
const onOpen = (record: any) => {
  console.log(record);
  receiptNo.value = record.receiptNo;
  payfeeID.value = record.payfeeID;
  // record.receiptNo
  // 如果record.feeCategory其中包括红冲，那么就不允许冲账
  if (record.feeCategory.includes('红冲')) {
    message.error('该条记录已经红冲');
    return;
  } else {
    open.value = true;
  }
};
const handleOk = () => {
  console.log(submitForm);
  const data = {
    payfeeID: payfeeID.value,
    redAccountType: submitForm.redAccountType,
    redAccountReason: submitForm.redAccountReason,
    payUrl: submitForm.payUrl,
  };
  getChargeApi(data).then((res) => {
    if (res) {
      onSearch();
      message.success(res);
      open.value = false;
    } else {
      message.error('冲账失败');
      open.value = false;
    }
  });
};
const onReset = () => {
  searchFormRef.value.resetFields();
};
</script>

<style scoped>
:deep(.ant-form-item) {
  margin-bottom: 10px !important;
}
</style>
